package com.wtwd.campus.jdzc.controller;

import com.wtwd.campus.common.Constants;
import com.wtwd.campus.entity.ClassModeVo;
import com.wtwd.campus.entity.DeviceClassMode;
import com.wtwd.campus.entity.DeviceClassPattern;
import com.wtwd.campus.entity.DeviceInfo;
import com.wtwd.campus.jdzc.common.Constant;
import com.wtwd.campus.jdzc.common.RespCode;
import com.wtwd.campus.jdzc.common.RespEntity;
import com.wtwd.campus.jdzc.service.ValidService;
import com.wtwd.campus.service.DeviceClassPatternService;
import com.wtwd.campus.service.DeviceInfoService;
import com.wtwd.campus.service.RedisService;
import com.wtwd.campus.utils.CommandSendUtils;
import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: ldaoliang
 * @DateTime: 2022/2/14 16:31
 * @Description:
 * 课堂模式
 */
@RestController
@RequestMapping("/jdzc/classPattern")
public class JdzcClassPatternController {

    private static final Logger logger = LoggerFactory.getLogger(JdzcClassPatternController.class);
    @Autowired
    private DeviceInfoService deviceInfoService;
    @Autowired
    private DeviceClassPatternService deviceClassPatternService;
    @Autowired
    private ValidService validService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private CommandSendUtils commandSendUtils;

    /**
     * 课堂模式列表
     * @param studentId
     * @param request
     * @return
     */
    @GetMapping("/list/{studentId}")
    public RespEntity list(@PathVariable("studentId")Integer studentId, HttpServletRequest request){
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByStuId(studentId);
        if (deviceInfo == null) {
            return new RespEntity(RespCode.NO_DEVICE);
        }
        String token = request.getHeader(Constant.HEADER_TOKEN_KEY);
        boolean isCorrespond = validService.validStudentAndTokenCorrespond(studentId,token);
        if(!isCorrespond){
            return new RespEntity(RespCode.ILLEGAL_OPERATION);
        }
        List<DeviceClassPattern> deviceClassPatternList = deviceClassPatternService.getDeviceClassesPatternByDeviceId(deviceInfo.getDeviceId());
        return new RespEntity(RespCode.SUCCESS, deviceClassPatternList);
    }

    /**
     * 添加课堂模式
     * @param classModeVo
     * @param request
     * @return
     */
    @PostMapping("/add")
    public RespEntity add(@RequestBody ClassModeVo classModeVo,HttpServletRequest request){
        logger.info("添加课堂模式： param = {}",classModeVo);
        Integer studentId = classModeVo.getStuId();
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByStuId(studentId);
        if (deviceInfo == null) {
            return new RespEntity(RespCode.NO_DEVICE);
        }
        String token = request.getHeader(Constant.HEADER_TOKEN_KEY);
        int validResult = validService.validCanOperation(studentId,token);
        if(validResult == 0){
            return new RespEntity(RespCode.ILLEGAL_OPERATION);
        }else if(validResult == 1){
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        Integer sequence = getClassSequence(deviceInfo.getDeviceId());
        if (sequence == 0) {
            return new RespEntity(RespCode.CLASS_PATTERN_FULL);
        }
        //处理重复的开关
        String repeatTime = classModeVo.getList();
        String replace = repeatTime.replace(",", "");
        DeviceClassMode mode = new DeviceClassMode();
        mode.setEndTime(classModeVo.getEnd());
        mode.setImei(deviceInfo.getImei());
        mode.setSequence(sequence);
        mode.setCommandNumber(getCurTime());
        mode.setDeviceId(deviceInfo.getDeviceId());
        mode.setRepeatTime(replace);
        mode.setStartTime(classModeVo.getStart());
        mode.setOnOff(1);//默认开
        mode.setStatus(Constants.CLASSES_PATTERN_STAY_ADD);
        //在数据库添加一笔课堂模式数据
        int i = deviceClassPatternService.addDeviceClassPattern(mode);
        if (i > 0) {
            //指令下发进行添加课堂模式
            boolean isOnline = deviceOnline(deviceInfo.getImei());
            boolean sendResult = commandSendUtils.addClassMode(mode, isOnline, Constants.WX_COMMAND_USER_ID, false);
            if (sendResult) {
                return new RespEntity(RespCode.SUCCESS);
            }
        }
        return new RespEntity(RespCode.FAILED);
    }

    /**
     * 删除课堂模式
     * @param studentId
     * @param id
     * @param request
     * @return
     */
    @DeleteMapping("/delete/{studentId}/{id}")
    public RespEntity del(@PathVariable("studentId")Integer studentId,@PathVariable("id")Integer id,HttpServletRequest request){
        logger.info("删除课堂模式：studentId = {},id = {}",studentId,id);
        String token = request.getHeader(Constant.HEADER_TOKEN_KEY);
        int validResult = validService.validCanOperation(studentId,token);
        if(validResult == 0){
            return new RespEntity(RespCode.ILLEGAL_OPERATION);
        }else if(validResult == 1){
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByStuId(studentId);
        if(deviceInfo == null){
            return new RespEntity(RespCode.NO_DEVICE);
        }
        DeviceClassPattern classPattern = deviceClassPatternService.getClassModeById(id);
        if(!deviceInfo.getDeviceId().equals(classPattern.getDeviceId())){
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        if(classPattern.getStatus() != Constant.STATUS_NORMAL){
            return new RespEntity(RespCode.COMMAND_NOT_COMPLETE_CAN_NO_OPERATION);
        }
        String commandNumber = getCurTime();
        Integer i = deviceClassPatternService.updateClassPatternStatus2(id, Constants.CLASSES_PATTERN_STAY_DELETE, commandNumber);
        if (i > 0) {
            boolean isOnline = deviceOnline(deviceInfo.getImei());
            boolean b1 = commandSendUtils.delClassMode(deviceInfo.getImei(), commandNumber, classPattern.getSequence(), isOnline, Constants.WX_COMMAND_USER_ID, false);
            if (b1) {
                return new RespEntity(RespCode.SUCCESS);
            }
        }
        return new RespEntity(RespCode.FAILED);
    }

    /**
     * 更新课堂模式
     * @param classModeVo
     * @param request
     * @return
     */
    @PutMapping("/update")
    public RespEntity update(@RequestBody ClassModeVo classModeVo,HttpServletRequest request){
        Integer studentId = classModeVo.getStuId();
        Integer id = classModeVo.getId();
        String token = request.getHeader(Constant.HEADER_TOKEN_KEY);
        int validResult = validService.validCanOperation(studentId,token);
        if(validResult == 0){
            return new RespEntity(RespCode.ILLEGAL_OPERATION);
        }else if(validResult == 1){
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByStuId(studentId);
        if(deviceInfo == null){
            return new RespEntity(RespCode.NO_DEVICE);
        }
        DeviceClassPattern classPattern = deviceClassPatternService.getClassModeById(id);
        if(!deviceInfo.getDeviceId().equals(classPattern.getDeviceId())){
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        if(classPattern.getStatus() != Constant.STATUS_NORMAL){
            return new RespEntity(RespCode.COMMAND_NOT_COMPLETE_CAN_NO_OPERATION);
        }
        // 发送指令相关
        String repeatTime = classModeVo.getList();
        String replace = repeatTime.replace(",", "");
        String commandNumber = getCurTime();
        DeviceClassMode mode = new DeviceClassMode();
        mode.setEndTime(classModeVo.getEnd());
        mode.setImei(deviceInfo.getImei());
        mode.setSequence(classModeVo.getSequence());
        mode.setCommandNumber(commandNumber);
        mode.setDeviceId(deviceInfo.getDeviceId());
        mode.setRepeatTime(replace);
        mode.setStartTime(classModeVo.getStart());
        mode.setOnOff(1);//默认开
        mode.setStatus(Constants.CLASSES_PATTERN_STAY_UPDATE);
        //修改课堂模式的状态为待修改
        int i = deviceClassPatternService.updateClassPatternStatus2(classModeVo.getId(), Constants.CLASSES_PATTERN_STAY_UPDATE, commandNumber);
        if (i > 0) {
            //指令下发进行添加课堂模式
            boolean isOnline = deviceOnline(deviceInfo.getImei());
            boolean b1 = commandSendUtils.updateClassMode(mode, isOnline, Constants.WX_COMMAND_USER_ID, false);
            if (b1) {
                return new RespEntity(RespCode.SUCCESS);
            }
        }
        return new RespEntity(RespCode.FAILED);
    }

    /**
     * 根据id获取详情
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/detail/{id}")
    public RespEntity detail(@PathVariable("id")Integer id,HttpServletRequest request){
        DeviceClassPattern classPattern = deviceClassPatternService.getClassModeById(id);
        if(classPattern == null){
            return new RespEntity(RespCode.DATA_NOT_FOUND);
        }
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByDeviceId(classPattern.getDeviceId());
        if(deviceInfo == null){
            return new RespEntity(RespCode.NO_DEVICE);
        }
        String token = request.getHeader(Constant.HEADER_TOKEN_KEY);
        boolean validResult = validService.validStudentAndTokenCorrespond(deviceInfo.getStudentId(),token);
        if(!validResult){
            return new RespEntity(RespCode.ILLEGAL_OPERATION);
        }
        //处理课堂模式开关数据
        String repeatTime = classPattern.getRepeatTime();
        char[] chars = repeatTime.toCharArray();
        String s = ArrayUtils.toString(chars, ",");
        int length = s.length();
        String result = s.substring(1, length - 1);
        classPattern.setRepeatTime(result);
        return new RespEntity(RespCode.SUCCESS, classPattern);
    }


    /**
     * 获取一个课堂模式可用的序列号
     *
     * @param deviceId
     * @return
     */
    public Integer getClassSequence(Integer deviceId) {
        //获取该设备已经存在的课堂模式
        List<DeviceClassPattern> list = deviceClassPatternService.getDeviceClassesPatternByDeviceId(deviceId);
        List<Integer> seqList = new ArrayList<>();
        for (DeviceClassPattern classPattern : list) {
            seqList.add(classPattern.getSequence());
        }
        for (int i = 1; i <= 10; i++) {
            if (!seqList.contains(i)) {
                return i;
            }
        }
        return 0;
    }

    /**
     * 判断设备是否在线
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    public boolean deviceOnline(String imei) {
        boolean isOnline = redisService.hasKey(Constants.DEVICE_ONLINE_PREFIX + imei);
        logger.info("设备:【{}】: {}", imei, isOnline ? "在线" : "离线");
        return isOnline;
    }

    /**
     * 获取当前时间的时分秒（HHmmss）
     *
     * @return
     */
    public String getCurTime() {
        Date d = new Date();
        SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");
        String format = sbf.format(d);
        String[] split = format.split(":");
        String time = split[0].concat(split[1]).concat(split[2]);
        return time;
    }

}
